//
//  CYPersonalDetailsTableVC.m
//  CreditAddressBook
//
//  Created by LE on 15/12/25.
//  Copyright © 2015年 Lee. All rights reserved.
//

#import "CYPersonalDetailsTableVC.h"
#import "UIInfomationView.h"
#import "CYJumpsTool.h"
#import "CYCompanyUserTool.h"
#import "CYMeHttpTool.h"
#import "LEImagePicker.h"
#import "CYJsonInfo.h"
#import "MJExtension.h"
#import "MBProgressHUD+MJ.h"
#import "CYLoginHttpTool.h"

@interface CYPersonalDetailsTableVC ()

@property (weak, nonatomic) IBOutlet UIImageView *avatarIV;
@property (weak, nonatomic) IBOutlet UITextField *nickNameTF;
@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UILabel *userType;
@property (weak, nonatomic) IBOutlet UILabel *userStatusLabel;

@property(nonatomic, strong) CYUser *user;
@property(nonatomic, strong) CYCompanyUserModel *companyUser;

@property(nonatomic, strong) NSString *avatarPath;
@end

@implementation CYPersonalDetailsTableVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self userDefaults];
    self.navigationItem.title = @"个人信息";
    [self setupLogout];
    self.avatarIV.contentMode = UIViewContentModeScaleAspectFill;
}

/**
 *  获取用户数据以及设置初始化数据
 */
- (void)userDefaults {
    [CYCompanyUserTool getUserWithUseType:self.loadUserType user:^(CYUser *user) {
        if (user) {
            //从服务器获取最新用户信息
            [self userNewData];
        } else {
            [CYJumpsTool jumpToLogin:self];
            [self.navigationController popViewControllerAnimated:NO];
        }
    } companyUser:^(CYCompanyUserModel *companyUser) {
        if (companyUser) {
            //从服务器获取最新用户信息
            [self companyUserNewData];
        } else {
            [CYJumpsTool jumpToCompanyLogin:self];
            [self.navigationController popViewControllerAnimated:NO];
        }
    }];
}

/**
 *  从服务器获取最新用户信息
 */
- (void)userNewData {
    [CYMeHttpTool getUserStatusForSuccess:^(CYUser *user) {
        self.user = user;
    } failure:^(NSString *message, BOOL isLogin) {
        
    }];
}
/**
 *  从服务器获取最新企业用户信息
 */
- (void)companyUserNewData {
    [CYMeHttpTool getCompanyUserStatusForSuccess:^(CYCompanyUserModel *user) {
        self.companyUser = user;
    } failure:^(NSString *message, NSError *error) {
        
    }];
}
/**
 *  设置登出操作
 */
- (void)setupLogout {
    UIBarButtonItem *btn = [[UIBarButtonItem alloc]initWithTitle:@"登出" style:UIBarButtonItemStylePlain target:self action:@selector(logout)];
    btn.tintColor = [UIColor blackColor];
    self.navigationItem.rightBarButtonItem = btn;
}

- (void)logout {
    [UIInfomationView showAlertViewWithTitle:@"确认退出当前账号？" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
        if (buttonIndex == 1) {
            if (self.companyUser) {
                [CYCompanyUserTool logout];
            } else if (self.user) {
                [CYLoginHttpTool logout];
            }
            [CYJumpsTool jumpToMain:self.view];
        }
    }];
}
- (IBAction)changeAvatar:(UIButton *)sender {
    [[LEImagePicker new] showInController:self handler:^(UIImage *image) {
        [self uploadHeadPic:image];
    }];
}
/**
 *  头像上传
 */
- (void)uploadHeadPic:(UIImage *)image {
    [CYHttpTool postWithURL:[CYURL updateHeadPicrPath] params:nil image:image success:^(id json) {
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        //上传成功更新头像访问路径
        if (jsonInfo.isSuccess) {
            self.avatarPath = jsonInfo.message;
            //上传成功设置显示图片
            [self.avatarIV setImage:image];
            [self updateUser];
        }else {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        CYLog(@"头像上传服务器连接失败：%@", error);
        [MBProgressHUD hideHUDForView:self.view];
        switch (error.code) {
            case CYErrorCodeOverTime:
                [MBProgressHUD showError:CYServerConnectTimeOver];
                break;
                
            default:
                [MBProgressHUD showError:@"网络错误，请重新上传"];
                break;
        }
    } uploadProgress:nil];
}

/**
 *  更新用户信息
 */
- (void)updateUser {
    if (self.user) {
        CYUser *user = self.user;
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"userId"] = user.userId;
        params[@"token"] = user.token;
        if (self.avatarPath) {
            params[@"headPic"] = self.avatarPath;
        }
        if (self.nickNameTF.text) {
            params[@"nickName"] = self.nickNameTF.text;
        }
        
        [CYMeHttpTool updateUserWithParams:params success:^(id json) {
            //            CYLog(@"用户更新json:%@", json);
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                //返回的json是更新后的最新用户信息
                CYUser *user = [CYUser objectWithKeyValues:jsonInfo.data];
                //将最新的用户信息保存到沙盒
                [CYLoginHttpTool updateUserData:user];
                
                //更新完成发送通知：用户信息已更新。个人中心进行监听
                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
                if (user.nickName) {
                    userInfo[CYChangedNickName] = user.nickName;
                }
                if (user.headPic) {
                    userInfo[CYChangedHeadPic] = user.headPic;
                }
                if (!user.nickName && !user.headPic) {
                    userInfo = nil;
                }
                [CYNotificationCenter postNotificationName:CYNickNameDidChangeNotification object:nil userInfo:userInfo];
                
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:@"修改成功"];
            } else if(jsonInfo.isNoLogin) {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:@"用户信息已过期，请重新登录"];
                [CYLoginHttpTool logout];
                [CYJumpsTool jumpToLogin:self];
            } else {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showSuccess:jsonInfo.message];
            }
        } failure:^(NSError *error) {
            CYLog(@"更新用户信息服务器连接失败：%@", error);
            [MBProgressHUD hideHUDForView:self.view];
            switch (error.code) {
                case CYErrorCodeOverTime:
                    [MBProgressHUD showError:CYServerConnectTimeOver];
                    break;
                    
                default:
                    [MBProgressHUD showError:@"网络错误，请重新上传"];
                    break;
            }
        }];
    }
}

#pragma mark - UITextFieldDelegate
/**
 *  return键监听
 */
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    if (textField.text.length && self.user && ![self.user.nickName isEqualToString:self.nickNameTF.text]) {
        [UIInfomationView showAlertViewWithTitle:@"确认修改用户名？" message:nil cancelButtonTitle:@"取消" otherButtonTitles:@[@"确定"] clickAtIndex:^(NSInteger buttonIndex) {
            if (buttonIndex == 1) {
                [MBProgressHUD showMessage:@"修改中" toView:self.view];
                [self updateUser];
            }
        }];
    }
    [textField resignFirstResponder];
    return YES;
}

/**
 *  设置头像边框
 */
- (void)setupHeadPicProperty {
    self.avatarIV.layer.cornerRadius = 17;
    self.avatarIV.layer.masksToBounds = YES;
    self.avatarIV.layer.borderColor = [CYNaviThemeColor CGColor];
    self.avatarIV.layer.borderWidth = 2.5;
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view.window endEditing:YES];
}
@end
